#include <iostream>
#include <string>
#include <vector>

#include "Thrad.hpp"
#define NUM 4
int tickets = 100;

struct ThreadData
{
    ThreadData(const std::string &threadname, pthread_mutex_t *mutexlock)
        : name(threadname), mutex(mutexlock) {}
    ThreadData() {}

    std::string name;
    pthread_mutex_t *mutex;
};

void *getTickets(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        //对临界资源访问进行加锁
        pthread_mutex_lock(td->mutex);
        if (tickets > 0)
        {
            usleep(1000); // 模拟抢票花费的时间
            std::cout << td->name << "正在抢票,抢到的票编号是:" << tickets << std::endl;
            tickets--;
            //对临界资源进行解锁
            pthread_mutex_unlock(td->mutex);
        }
        else
        {
            std::cout << "无票可抢!" << std::endl;
            pthread_mutex_unlock(td->mutex);
            break;
        }
    }
    return nullptr;
}

int main()
{
    // 定义与初始化锁
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);

    // 定义每一个线程的数据结构体
    std::vector<pthread_t> tids(NUM);
    for (int i = 0; i < NUM; i++)
    {
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "thread-%d", i + 1);

        ThreadData *td = new ThreadData(buffer, &lock);
        pthread_create(&tids[i], nullptr, getTickets, (void *)td);
    }

    for (int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    // 释放锁
    pthread_mutex_destroy(&lock);
    return 0;
}